package com.aqgj.User.web;

import com.aqgj.Role.bean.Role;
import com.aqgj.User.bean.UserVo;
import com.aqgj.User.bean.User;
import com.aqgj.User.service.UserManager;
import com.aqgj.common.BaseController;
import com.aqgj.shiro.PasswordHash;
import com.aqgj.util.GenericsUtils;
import com.aqgj.util.JsonWrapper;
import com.aqgj.util.StringUtils;
import com.ztc.ZtcTransport.bean.ZtcTransport;
import com.ztc.ZtcTransport.service.ZtcTransportManager;
import com.ztc.ZtcWallet.service.ZtcWalletManager;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.*;


@Controller
@RequestMapping("ztc/sysUser")
public class UserAction extends BaseController{

    @Autowired
    private UserManager userManager;
    @Autowired
    private ZtcWalletManager ztcWalletManager;
    @Autowired
    private ZtcTransportManager ztcTransportManager;
    @Autowired
    private PasswordHash passwordHash;

    /**
     * 当前公司全部用户.
     *
     * @return 全部用户
     */
    @RequestMapping("getUser")
    @ResponseBody
    public HashMap<String, Object> getUser(HttpSession session) {
        User user = (User) session.getAttribute("userInfo");
        return userManager.getUser(user);
    }

    /**
     * 根据cid添加登录用户.
     *
     * @param user  用户
     * @param cName 公司名字
     * @return
     */
    @RequestMapping("saveUser")
    @ResponseBody
    public HashMap<String, Object> saveUser(User user, String cName,String pageStatus) {
        if (GenericsUtils.isEmpty(cName)) {
            return JsonWrapper.failureWrapperMsg("添加用户时请选择归属公司！");
        }
        ZtcTransport ztcTransport = ztcTransportManager.findUniqueBy("fullName", cName);
        if (ztcTransport == null) {
            return JsonWrapper.failureWrapperMsg("当前选择的公司不存在！");
        }
        if ("add".equals(pageStatus)) {
            user.setTransportId(ztcTransport.getId());
            user.setCurrTime(new Date());
            user.setStatus("1");
            String uid = userManager.save(user);
            if (uid == null) {
                return JsonWrapper.failureWrapperMsg("添加失败，请稍后重试！");
            }
        }else{
            User user1=userManager.get(user.getId());
            user1.setRemark(user.getRemark());
            user1.setTelPhone(user.getTelPhone());
            user1.setName(user.getName());
            String uid = userManager.save(user1);
            if (uid == null) {
                return JsonWrapper.failureWrapperMsg("修改失败，请稍后重试！");
            }else{
                return JsonWrapper.successWrapper("修改成功！");
            }
        }
        return JsonWrapper.successWrapper("添加成功！");
    }


    @PostMapping("registerUser")
    @ResponseBody
    public HashMap<String, Object> registerUser(User user) {
        userManager.saveRegisterUser(user);
        return JsonWrapper.successWrapper("注册成功");
    }

    /**
     * 更改当前用户密码.
     *
     * @param oPassword 原密码
     * @param nPassword 新密码
     * @return
     */
    @RequestMapping("updatePassword")
    @ResponseBody
    public HashMap<String, Object> updatePassword(String oPassword, String nPassword, HttpSession session) {
        User user = (User) session.getAttribute("userInfo");
        String salt = user.getSalt();
        String pwd = passwordHash.toHex(oPassword, salt);
        if (!pwd.equals(user.getPassword())) {
            return JsonWrapper.failureWrapperMsg("原密码输入错误！");
        }
        String pwd1 = passwordHash.toHex(nPassword, salt);
        if (pwd1.equals(user.getPassword())) {
            return JsonWrapper.failureWrapperMsg("新密码不能与原密码一致！");
        }
        user.setPassword(pwd1);
        userManager.save(user);
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return JsonWrapper.successWrapper("密码已更改！");
    }

    /**
     * 重置用户密码.
     *
     * @param uid       用户
     * @param nPassword 新密码
     * @return
     */
    @RequestMapping("updatePasswordByUid")
    @ResponseBody
    public HashMap<String, Object> updatePasswordByUid(String uid, String nPassword) {
        if (GenericsUtils.isEmpty(uid)) {
            return JsonWrapper.failureWrapperMsg("请选择用户！");
        }
        User user = userManager.get(uid);
        if (user == null) {
            return JsonWrapper.failureWrapperMsg("操作失败，不存在该用户！");
        }
        String salt = user.getSalt();
        String pwd = passwordHash.toHex(nPassword, salt);
        user.setPassword(pwd);
        userManager.save(user);
        SecurityUtils.getSubject().logout();
        return JsonWrapper.successWrapper("密码已重置");
    }

    //获取公司列表信息（用于添加用户）
    @RequestMapping("getCompanyList")
    @ResponseBody
    public HashMap<String, Object> getCompanyList(HttpSession session) {
        User user = (User) session.getAttribute("userInfo");
        ZtcTransport ztcTransport = ztcTransportManager.get(user.getTransportId());
        if (ztcTransport == null) {
            return JsonWrapper.failureWrapperMsg("获取失败！");
        }
        List<ZtcTransport> ztcTransports = null;
        HashMap<String, Object> map = null;
        List<HashMap<String, Object>> result = new ArrayList<>();
        if ("0".equals(String.valueOf(ztcTransport.getType()))) {
            ztcTransports = ztcTransportManager.findBy("status", 3);//已通过审核的公司
            if (ztcTransports.size() > 0) {
                for (ZtcTransport z : ztcTransports) {
                    map = new HashMap<>();
                    map.put("cId", z.getId());
                    map.put("cName", z.getFullName());
                    result.add(map);
                }
            }
        } else {
            map = new HashMap<>();
            map.put("cId", ztcTransport.getId());
            map.put("cName", ztcTransport.getFullName());
            result.add(map);
        }
        return JsonWrapper.successWrapper(result);
    }

    /**
     * 获取用户详情.
     *
     * @param uid 用户id
     * @return
     */
    @RequestMapping("getUserDetail")
    @ResponseBody
    public HashMap<String, Object> getUserDetail(String uid) {
        if (GenericsUtils.isEmpty(uid)) {
            return JsonWrapper.failureWrapperMsg("获取失败，参数错误！");
        }
        User user = userManager.get(uid);
        if (user == null) {
            return JsonWrapper.failureWrapperMsg("初始化失败，没有该用户！");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("uName", user.getName());
        map.put("uTelPhone", user.getTelPhone());
        map.put("uAccount", user.getAccount());
        map.put("uCurrTime", user.getCurrTime());
        map.put("uRemark", user.getRemark());
        map.put("uStatus", user.getStatus());
        if (user.getTransportId() != null) {
            ZtcTransport ztcTransport = ztcTransportManager.get(user.getTransportId());
            map.put("cName", ztcTransport == null ? "" : ztcTransport.getFullName());
        }
        return JsonWrapper.successWrapper(map);
    }

    /**
     * 冻结用户/启用用户.
     *
     * @param uid 用户id
     * @return
     */
    @RequestMapping("lockAndUnlock")
    @ResponseBody
    public HashMap<String, Object> lockAndUnlock(String uid, String status) {
        if (GenericsUtils.isEmpty(uid)) {
            return JsonWrapper.failureWrapperMsg("获取失败，参数错误！");
        }
        User user = userManager.get(uid);
        if (user == null) {
            return JsonWrapper.failureWrapperMsg("操作失败，没有该用户！");
        }
        user.setStatus(status);
        userManager.save(user);
        return JsonWrapper.successWrapper("操作成功！");
    }

    /**
     * 用户管理页
     *
     * @return
     */
    @GetMapping("/manager")
    public String manager() {
        return "admin/user/table_user";
    }

    /**
     * 用户管理列表
     *
     * @param userVo
     * @return
     */
    @PostMapping("/dataGrid")
    @ResponseBody
    public Object dataGrid(UserVo userVo, Integer pageSize, Integer pageNumber) {
        return userManager.selectDataGrid(userVo,pageSize,pageNumber);
    }

    /**
     * 添加用户页
     *
     * @return
     */
    @GetMapping("/addPage")
    public String addPage() {
        return "admin/user/userAdd";
    }

    /**
     * 添加用户
     *
     * @param userVo
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public Object add(UserVo userVo,HttpSession session) {
        User user=(User)session.getAttribute("userInfo");
        List<User> list = userManager.selectByLoginName(userVo);
        if (list != null && !list.isEmpty()) {
            return renderError("登录名已存在!");
        }
        String salt = StringUtils.getUUId();
        String pwd = passwordHash.toHex(userVo.getPassword(), salt);
        userVo.setSalt(salt);
        userVo.setPassword(pwd);
        userManager.insertByVo(userVo,user.getTransportId());
        return renderSuccess("添加成功");
    }

    /**
     * 编辑用户页
     *
     * @param id
     * @param
     * @return
     */
    @PostMapping("/editPage")
    @ResponseBody
    public Object editPage(String id) {
        User user = userManager.selectById(id);
        Set<Role> rolesList = user.getRoles();
        List<String> ids = new ArrayList<>();
        for (Role role : rolesList) {
            ids.add(role.getId());
        }
        Map<String,Object> userMap = new HashMap<>(10);
        userMap.put("roleIds", ids);
        userMap.put("user", user);
        return renderSuccess(userMap);
    }

    /**
     * 编辑用户
     *
     * @param userVo
     * @return
     */
    @PostMapping("/edit")
    @ResponseBody
    public Object edit(UserVo userVo) {
        List<User> list = userManager.selectByLoginName(userVo);
        if (list != null && !list.isEmpty()) {
            if (!userVo.getId().equals(list.get(0).getId())) {
                return renderError("登录名已存在!");
            }
        }
        //更新密码
        if (StringUtils.isNotBlank(userVo.getPassword())) {
            User user = userManager.selectUserById(userVo.getId());
            String salt = user.getSalt();
            String pwd = passwordHash.toHex(userVo.getPassword(), salt);
            userVo.setPassword(pwd);
        }
        userManager.updateByVo(userVo);
        return renderSuccess("修改成功！");
    }

    /**
     * 修改密码
     *
     * @param oldPwd
     * @param pwd
     * @return
     */
    @PostMapping("/editUserPwd")
    @ResponseBody
    public Object editUserPwd(UserVo userVo, String oldPwd, String pwd) {
        List<User> list = userManager.selectByLoginName(userVo);
        if (list == null || list.isEmpty()) {
            return renderError("用户不存在!");
        }
        User user = list.get(0);
        if (user == null) {
            return renderError("用户不存在!");
        }
        String salt = user.getSalt();
        if (!user.getPassword().equals("12")) {
            return renderError("原密码不正确!");
        }
        userManager.updatePwdByUserId(user.getId(), "122121");
        return renderSuccess("密码修改成功！");
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @PostMapping("/delete")
    @ResponseBody
    public Object delete(String id) {
        String currentUserId = getUserId();
        if (id.equals(currentUserId)) {
            return renderError("不可以删除自己！");
        }
        userManager.deleteUserById(id);
        return renderSuccess("删除成功！");
    }

}